package com.zzy.demo;

import java.io.File;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import com.zzy.common.DayUtil;

import cn.hutool.core.io.FileUtil;

/**
 * 订阅主题
 * @author Administrator
 *
 */
public class SubscribeSample {
	
	public static final String path ="D:\\tick";	
	
	
    public static void main(String[] args) {

        String broker = "tcp://14.22.112.2:8099";
        String topic = "002967";
        String username = "yuexingzhe89757";
        String password = "DumIj#d^";
        String clientid = "2c1485c7-d950-43a2-8d3a-277ff16053fc";
        int qos = 0;

        try {
            MqttClient client = new MqttClient(broker, clientid, new MemoryPersistence());
            // 设置连接参数
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(true);
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            options.setConnectionTimeout(60);
            options.setKeepAliveInterval(60);
            // 设置回调
            client.setCallback(new MqttCallback() {

                public void connectionLost(Throwable cause) {
                    System.out.println("connectionLost: " + cause.getMessage());
                }

                public void messageArrived(String topic, MqttMessage message) {
                    String text =  new String(message.getPayload());
                    text = text + ";";
                    
                    System.out.println("topic: " + topic +"____"+text);
                    String day = DayUtil.getNowDay();
                    File syncFile = new File(path + topic +"_"+day+".text");
                    FileUtil.appendUtf8String(text, syncFile.getAbsolutePath());

                }

                public void deliveryComplete(IMqttDeliveryToken token) {
                    System.out.println("deliveryComplete---------" + token.isComplete());
                }

            });
            client.connect(options);
            client.subscribe(topic, qos);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
